<template>
  <div class="staff-photo">
    <Row class="title-top mb-10">
      <h2>证件照</h2>
    </Row>
    <Row>
      <Input
        type="text"
        search
        v-model.trim="keyword"
        @on-search="queryPhotoList"
        @enter="queryPhotoList"
        enter-button
        placeholder="搜索姓名、用户名"
        style="width:20%"
        clearable
      />
    </Row>
    <Row>
      <div class="tag-photo mt-10">
        <span class="mt-3 mr-10">照片类型:</span>
        <div
          v-for="item in tabList"
          :key="item.id"
          :class="[{ active: tagId === item.id }, 'tag-item', 'mr-10']"
          @click="changTab(item.id)"
        >
          {{ item.name }}
        </div>
      </div>
    </Row>
    <Row class="mt-10 mb-10">
      <ButtonGroup>
        <Button @click="uploadBtn" class="cb-icon" icon="md-cloud-upload">上传</Button>
        <Button :disabled="!tableData.length" class="cb-icon" icon="md-exit">导出</Button>
        <Button :disabled="!tableData.length" class="cb-icon" icon="ios-trash">删除</Button>
      </ButtonGroup>
    </Row>
    <!--有数据 scroll -->
    <Scroll class="scroll-box" :distance-to-edge="-50" :on-reach-bottom="loadMore" :height="height">
      <Row class="photo-box" v-if="tableData.length">
        <div
          class="photo-item"
          :class="item.select ? 'active' : ''"
          v-for="(item, index) in tableData"
          :key="index"
        >
          <div class="img-select" @click="item.select = !item.select" title="选中">
            <Icon type="md-checkmark" />
          </div>
          <div class="img-box">
            <img
              @click="previewImg(item)"
              :src="item.image"
              @load="
                target => {
                  AutoSize(target.target, 168);
                }
              "
              height="168"
              width="168"
              alt
              srcset
            />
            <div class="img-del">
              <div title="删除" @click="showDeleteOneModal(item.id)" class="delete-btn">
                <Icon type="ios-trash" :size="12" color="#fff" />
              </div>
            </div>
          </div>
          <div class="img-des">
            <div class="name">{{ item["person.name"] }}</div>
            <div class="code">{{ item["person.code"] }}</div>
          </div>
        </div>
      </Row>
      <BaseEmpty v-else title="暂无图片数据"></BaseEmpty>
    </Scroll>
    <!--上传照片 -->
    <BaseModal
      v-model="showUploadPhoto"
      title="上传证件照"
      width="1200"
      :closable="false"
      :mask-closable="false"
    >
      <div class="upload-header mb-15">
        <span @click="showViewImage = true">选择证件照类型：</span>
        <RadioGroup v-model="tagType" @on-change="clearFiles">
          <Radio v-for="item in tabList" :key="item.id" :disabled="!disabled" :label="item.id">{{
            item.name
          }}</Radio>
        </RadioGroup>
      </div>
      <!-- 上传组件 upload调用子组件的方法clearFile,将:disabled.sync="disabled"改成:uploaded.sync="disabled",即文件上传or移除之后都可以进行类型切换-->
      <upload-photo ref="upload" :tagType="tagType" :uploaded.sync="disabled"></upload-photo>
      <div slot="footer" class="upload-footer">
        <p>
          <span class="upload-des">证件照请用“用户名（一般为学号或工号）”命名。</span
          >未按要求命名或用户名在系统中不存在的照片将无法上传成功
        </p>
        <Button @click="closeUpload">关闭</Button>
      </div>
    </BaseModal>
    <!--关闭提示框 -->
    <BaseModal
      v-model="showComfirUpload"
      title="取消上传"
      type="warning"
      simple="false"
      :mask-closable="true"
      @on-ok="cancelUpload"
      @on-cancel="showComfirUpload = false"
      >关闭弹窗将清除待上传文件/终止上传进程。确认关闭吗？</BaseModal
    >
    <!--预览图片 -->
    <view-photo
      :src="ImageView.src"
      :title="ImageView.imgTitle"
      :show.sync="ImageView.previewModal"
    ></view-photo>
    <!--删除单个图片 -->
    <BaseModal
      v-model="showDetelPhoto"
      title="确定删除"
      width="350"
      ok-type="error"
      ok-text="删除"
      type="warning"
      simple="false"
      :mask-closable="true"
      @on-ok="deleOneOk"
      @on-cancel="showDetelPhoto = false"
      >此数据将被删除，确认操作吗？</BaseModal
    >
  </div>
</template>
<script lang="ts">
import { Component, Vue, Prop } from "vue-property-decorator";
import { Tools } from "@/model/tools.ts";
import { BASE64, AutoSize } from "@utils/tools.ts";
import { getWhole, queryPhotoData, deleteData } from "@/api/service.js";
import { WholeData, ImageView, ParamData } from "@/store/interface.ts";
import BaseEmpty from "@components/iv-empty/BaseEmpty.vue";
import BaseModal from "@components/iv-modal/BaseModal.vue";
import UploadPhoto from "@views/UploadPhoto.vue";
import ViewPhoto from "@views/ViewPhoto.vue";

@Component({
  components: {
    BaseEmpty,
    BaseModal,
    UploadPhoto,
    ViewPhoto
  }
})
export default class StaffPhoto extends Tools {
  public $refs!: {
    upload: any;
  };
  private currIndex: number = 0; // tag标签
  private totalSize: number = 0; // 总数
  private keyword: string = ""; //模糊查询
  private tagId: number = 0; //tag类型
  private tabList: Array<any> = [];
  private tagType: string = ""; // 弹框切换照片类型
  private showUploadPhoto: boolean = false;
  private showComfirUpload: boolean = false; //关闭弹窗
  private disabled: boolean = true; // 点击上传则不可切换照片类型
  private showViewImage: boolean = false; //预览图片
  private showDetelPhoto: boolean = false; //删除单个photo
  private tableData: Array<any> = []; // 图片集合列表
  private totalHeight: number = 0;
  private topHeight: number = 0;
  private delId: string = ""; // 单个照片的删除
  private type: string = "personPhoto";
  private AutoSize: any = AutoSize; // 引入export 方法
  private staffPhoto: WholeData = {
    dictName: "",
    filter: true,
    pageNumber: 1,
    pageSize: 10
  };

  private photoParam: ParamData = {
    type: this.type,
    pageNumber: 1,
    pageSize: 10,
    criteria: "",
    includeAttributes: ["image", "person.code", "person.name"]
  };

  private ImageView: ImageView = {
    src: "",
    imgTitle: {},
    previewModal: false
  };

  /**
   * 照片类型
   */
  private async getWhole() {
    let params = Object.assign(this.staffPhoto, { dictName: "photoType" });
    const [err, data] = await getWhole(params);
    if (err) {
      let msg = err.message || "获取照片类型异常";
      this.$Message.error(msg);
      return;
    }
    if (!data) return;
    this.tabList = data.rows;
    this.tagId = this.tabList[0].id;
    this.queryPhotoList();
  }

  /**
   * 滚动条的高度
   */
  private get height() {
    return this.totalHeight - this.topHeight;
  }

  /**
   * 请求参数
   */
  private get criteria() {
    return BASE64.encode(
      JSON.stringify([
        ["OR", [["person.code", "ilike", this.keyword], ["person.name", "ilike", this.keyword]]],
        ["photoType", "eq", this.tagId]
      ])
    );
  }

  private get selectDelParams() {
    return {
      //按勾选删除
      type: this.type,
      ids: [this.delId]
    };
  }

  private get deleteParams() {
    return this.selectDelParams;
  }

  /**
   * 照片集合
   */
  private async queryPhotoList() {
    const _this = this;
    _this.photoParam.criteria = _this.criteria;
    const [err, data] = await queryPhotoData(_this.photoParam);
    if (err) {
      let msg = err.message || "获取证件照信息异常";
      _this.$Message.error(msg);
      return;
    }
    this.tableData = data.rows;
    this.totalSize = data.totalSize;
  }
  private changTab(id) {
    this.tagId = id;
    this.queryPhotoList();
  }

  private uploadBtn() {
    //切换类型可点击
    this.clearFiles();
    this.showUploadPhoto = true;
    this.tagType = this.tabList[0].id;
  }

  /**
   * 预览图片
   */
  private previewImg(obj) {
    this.ImageView.imgTitle = obj["person.name"] + obj["person.code"];
    this.ImageView.src = obj.image;
    this.ImageView.previewModal = true;
  }

  private loadMore() {
    return new Promise(async (resolve, reject) => {
      let { pageNumber, pageSize } = this.photoParam;
      if (pageNumber * pageSize >= this.totalSize) {
        resolve();
        return;
      }
      this.photoParam.pageNumber++;
      console.log(this.photoParam, "更多加载");
      const [err, data] = await queryPhotoData(this.photoParam);
      if (err) {
        let msg = err.message || "加载更多数据异常";
        this.$Message.error(msg);
        reject();
        return;
      }
      resolve();
      this.totalSize = data.totalSize;
      this.tableData = this.tableData.concat(data.rows);
    });
  }

  /**
   * 删除单个图片
   */
  private showDeleteOneModal(id) {
    this.delId = id;
    this.showDetelPhoto = true;
  }

  private deleOneOk() {
    this.showDetelPhoto = false;
    this.delePhotoData();
  }

  private async delePhotoData() {
    const [err, data] = await deleteData(this.deleteParams);
    if (err) {
      let msg = err.message || "删除该信息异常";
      this.$Message.error(msg);
      return;
    }
    this.$Message.success("删除成功");
    this.queryPhotoList();
  }

  /**
   * 点击取消上传调用
   */
  private cancelUpload() {
    this.clearFiles();
    this.showUploadPhoto = false;
    this.showComfirUpload = false;
    this.queryPhotoList();
  }

  private closeUpload() {
    let uploadPhoto = !this.disabled;
    if (uploadPhoto) {
      this.showComfirUpload = true; //关闭弹窗
    } else {
      this.showUploadPhoto = false;
      this.queryPhotoList();
    }
  }

  /**
   * 弹窗切换照片类型
   */
  private clearFiles() {
    //证件照类型修改时清除文件，即调用子组件clearFile()方法清空已上传列表数据
    this.$refs.upload.clearFile();
  }

  mounted() {
    //强类型,需要做定义
    let el: any = this.$el.children[0];
    let appDom: any = document.querySelector(".app-content");
    this.topHeight = el.offsetHeight;
    this.totalHeight = appDom.offsetHeight - 60;
    this.getWhole();
  }
}
</script>
<style lang="stylus" scoped>
@import '~stylus/variable.styl'

.staff-photo {
  >>>.ivu-input-icon-clear {
    margin-right: 50px
  }
  position: relative
  .scroll-box>>>.ivu-scroll-container {
    overflow-y: auto
  }
  .tag-photo {
    display: flex
    .tag-item {
      padding: 3px 5px
      border-radius: 4px
      cursor: pointer
    }
    .active {
      background: $primary-color
      color: #fff
      transition: 0.3s
    }
  }
  .photo-box {
    display: flex
    flex-flow: row wrap
    .photo-item {
      width: 144px
      height: 230px
      margin: 10px
      position: relative
      &:hover {
        background: #edf3fe
        .img-select {
          visibility: visible
        }
        .img-del {
          bottom: 0
        }
      }
      .img-box {
        position: absolute
        cursor: pointer
        width: 120px
        height: 168px
        top: 0
        left: 50%
        overflow: hidden // 解决了底部阴影删除层的展示,以及图片过宽or过高的隐藏
        transform: translate(-50%, 15px)
        img {
          position: absolute
          top: 0
          left: 50%
          transform: translateX(-50%)
        }
      }
    }
    .img-des {
      position: absolute
      bottom: 0
      width: 100%
      height: 47px
      text-align: center
      .name {
        font-weight: 700
        overflow: hidden
        text-overflow: ellipsis
        white-space: nowrap
        word-break: break-all
      }
    }
    .img-select {
      position: absolute
      visibility: hidden
      top: 5px
      left: 2px
      width: 20px
      height: 20px
      border-radius: 50%
      background: #97bff9
      text-align: center
      line-height: 20px
      color: #fff
      font-size: 12px
      z-index: 2
      &:hover {
        background: #4481F1
        cursor: pointer
      }
    }
    .img-del {
      display: flex
      background: rgba(0, 0, 0, 0.3)
      width: 120px
      height: 25px
      position: absolute
      bottom: -50px // 从bottom:-50px渐变到bottom:0px
      justify-content: flex-end
      align-items: center
      transition: 0.2s ease-in-out // 动画
      .delete-btn {
        margin-right: 5px
        cursor: pointer
        width: 20px
        height: 20px
        text-align: center
        :hover {
          background: #3F2B11
        }
      }
    }
  }
}
.upload-footer {
  display: flex
  justify-content: space-between
  width: 100%
  .upload-des {
    color: #f19000
  }
}
</style>
